package com.silverbox.sweeporder.service.shopcart.impl;

import java.io.Serializable;
import java.util.*;

import com.silverbox.core.util.*;
import com.silverbox.shopper.entity.Shopper;
import com.silverbox.sweeporder.controller.shopcart.entryvo.*;
import com.silverbox.sweeporder.controller.waimai.entryvo.CouponBaseDto;
import com.silverbox.sweeporder.service.index.IndexService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.silverbox.core.result.CoreResponse;
import com.silverbox.core.result.CoreResponse.StatusInfo;
import com.silverbox.shopper.dubboApi.info.ShopperInfoServiceApi;
import com.silverbox.sweeporder.common.CommConstant;
import com.silverbox.sweeporder.common.Constants;
import com.silverbox.sweeporder.common.util.SweepOrderUtils;
import com.silverbox.sweeporder.controller.index.vo.DiscountInfoVO;
import com.silverbox.sweeporder.controller.index.vo.ShopperConfigExtend;
import com.silverbox.sweeporder.controller.shopcart.outvo.CategoryShopCartBuyIdVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.CategoryShopCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.GoodsCartItemVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.GoodsCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.IndexCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.IndexGoodsVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.SaveShopCartVO;
import com.silverbox.sweeporder.controller.shopcart.outvo.ShopCartVO;
import com.silverbox.sweeporder.service.redis.RedisService;
import com.silverbox.sweeporder.service.shopcart.ShopCartService;
import com.silverbox.sweeporder.service.waimai.WaimaiOrderService;
import com.silverbox.waimai.dubboApi.goodscart.GoodsCartServiceApi;
import com.silverbox.waimai.entity.GoodsCart;
import com.silverbox.waimai.entity.GoodsCartDetail;
import com.silverbox.waimai.entity.Waimai;
import com.silverbox.waimai.entity.extend.GoodsCartAndDetail;
import com.silverbox.waimai.entity.extend.GoodsCartExtend;

@Service
//@Transactional
public class ShopCartServiceImpl implements ShopCartService {
	private static Logger logger = LoggerFactory.getLogger(ShopCartServiceImpl.class);
	@Autowired
	private GoodsCartServiceApi goodsCartServiceApi;
	
	@Autowired
	private ShopperInfoServiceApi shopperInfoServiceApi;
	
	@Autowired
	private WaimaiOrderService waimaiOrderService;

	@Autowired
    private IndexService indexService;
	
	@Autowired
	private RedisService<Serializable, Object> redisService;

    @Value("${marketing.url}")
    public String marketingUrl;
	
	@Override
	public List<GoodsCartAndDetail> getShopCart(Integer storeId, String tableName, String buyerId, Integer clientOrderMode, Integer firstPayMent, Integer isOpenDeskmateSinglePoint) {
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		List<GoodsCartAndDetail> goodsList = null;
		logger.info("params:"+tableName+"、"+buyerId);
		if (!StringUtils.isEmpty(tableName)) {
			if (new Integer(1).equals(firstPayMent) && new Integer(1).equals(isOpenDeskmateSinglePoint)) {
			    logger.info("根据tableName、buyerId查询");
				goodsList = goodsCartServiceApi.getGoodsCartByTableNoAndBuyerId(storeId, tableName, startDate, endDate, buyerId);
			} else {
                logger.info("根据tableNo、buyerId查询");
                goodsList = goodsCartServiceApi.getGoodsCartByTableNo(storeId, tableName, startDate, endDate,clientOrderMode);
			}
		} else {
            logger.info("根据buyerId查询");
            goodsList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId, startDate, endDate,clientOrderMode);
		}
		return goodsList;
	}

	@Override
	public void deleteGoodsCart(Integer storeId, String buyerId, String tableName,Integer mustOrder,String isClearOrder) {
		// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		if (!StringUtils.isEmpty(tableName)) {
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
				// 如果开启同桌单点就根据桌台和顾客Id删除
				goodsCartServiceApi.removeGoodsCartByTableNoAndBuyerId(storeId, tableName, mustOrder, buyerId);
				
			} else {
				goodsCartServiceApi.removeGoodsCartByTableNo(storeId, tableName, mustOrder);
			}
		} else {
			goodsCartServiceApi.removeGoodsCartByBuyerId(storeId, buyerId, mustOrder);
		}
		if (!Utils.isEmpty(isClearOrder) && "1".equals(isClearOrder)) {
			List<Waimai> list=waimaiOrderService.getMyUnPayOrder(storeId, tableName, buyerId);
			if(!Utils.isEmpty(list) && list.size() > 0){
				for (Waimai waimai : list) {
					waimai.setOrderStatus(12);
					waimaiOrderService.updateWaimaiStauts(waimai);
				}
			}
			
			
		}

	}

	@Override
	public Integer updateGoodsCartById(GoodsCart goodsCart) {
		return goodsCartServiceApi.updateGoodsCart(goodsCart);
	}

	@Override
	public GoodsCartAndDetail getShopCartById(Integer goodsCartId) {
		return goodsCartServiceApi.getGoodsCartById(goodsCartId);
	}

	@Override
	public Integer getShopCartByPack(GoodsCartExtend goodsCart) {
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		goodsCart.setStartDate(startDate);
		goodsCart.setEndDate(endDate);
		Integer count = 0;
		if(StringUtils.isNotEmpty(goodsCart.getTableNo())){
			count = goodsCartServiceApi.getGoodsCartPackCountByTableNo(goodsCart);
		}else{
			count = goodsCartServiceApi.getGoodsCartPackCountById(goodsCart);
		}
		return count;
	}

	@Override
	public boolean deleteShopCartByPack(GoodsCartExtend goodsCart) {
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		goodsCart.setStartDate(startDate);
		goodsCart.setEndDate(endDate);
		boolean flag = false;
		Integer count = 0;
		if(StringUtils.isNotEmpty(goodsCart.getTableNo())){
			count = goodsCartServiceApi.deleteGoodsPackByTableNo(goodsCart);
		}else{
			count = goodsCartServiceApi.deleteGoodsPackByBuyerId(goodsCart);
		}
		if(count>0){
			flag=true;
		}
		return flag;
	}

	@Override
	public void updateGoodsCartByGoodsDesc(Integer storeId, String tableName, String buyerId, String goodsDesc) {
		if(!StringUtils.isEmpty(tableName)){
			goodsCartServiceApi.updateGoodsCartPackByTableNo(storeId, tableName, goodsDesc);
		}else{
			goodsCartServiceApi.updateGoodsCartPackByBuyerId(storeId, buyerId, goodsDesc);
		}
	}

	@Override
	public CoreResponse<IndexCartVO> getShopCartbyIndex(ShopCartIndexQueryDto shopCartIndexQueryVo) {
		CoreResponse<IndexCartVO> res = new CoreResponse<IndexCartVO>();

        Integer storeId = shopCartIndexQueryVo.getStoreId();
        String tableName = shopCartIndexQueryVo.getTableName();
        String buyerId = shopCartIndexQueryVo.getBuyerId();
        Integer clientOrderMode = shopCartIndexQueryVo.getClientOrderMode();

        String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		List<GoodsCartAndDetail> goodsList = null;
		// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//获取购物车商品信息
		if (!StringUtils.isEmpty(tableName)) {
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
				// 如果开启同桌单点就根据桌台和顾客Id查询
				goodsList = goodsCartServiceApi.getGoodsCartByTableNoAndBuyerId(storeId, tableName, startDate, endDate, buyerId);
			} else {
				goodsList = goodsCartServiceApi.getGoodsCartByTableNo(storeId, tableName, startDate, endDate,clientOrderMode);
			}
		} else {
			goodsList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId, startDate, endDate,clientOrderMode);
		}
		
		if (CollectionUtils.isEmpty(goodsList)) {
			res.setData(null);
			res.setMsg("购物车暂无数据");
			return res;
		}
		//购物车商品总价
		Double totalPrice = 0.0;
		//购物车自己购买商品数量
		double tableMyCount = 0.0;
		//购物车同桌购买商品数量
		double tableOtherCount = 0.0;
		//购物车同桌购买商品总价
		double tableOtherPrice = 0.0;
        //购买原总价
        double totalOriginalPrice = 0D;
        //购买总价
        double totalBuyOriginalPrice = 0D;
        double oneGoodsPrice = 0D;

		Map<String, List<IndexGoodsVO>> myGoods = new HashMap<String, List<IndexGoodsVO>>();
		Map<String, List<IndexGoodsVO>> otherGoods = new HashMap<String, List<IndexGoodsVO>>();
		Map<String, List<IndexGoodsVO>> mustGoods = new HashMap<String, List<IndexGoodsVO>>();
		List<IndexGoodsVO> myGoodsList = new ArrayList<IndexGoodsVO>();
		List<IndexGoodsVO> otherGoodsList = new ArrayList<IndexGoodsVO>();
		List<IndexGoodsVO> mustGoodsList = new ArrayList<IndexGoodsVO>();
		//是否享受会员价
        boolean isEnjoyMemberPrice = indexService.isEnjoyMemberPrice(shopCartIndexQueryVo, shopperConfigExt);
        // 组装同桌点餐菜品数据
		for (GoodsCartAndDetail goods : goodsList) {
            //20200612会员价回显

            Double buyPrice = (!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice) ? goods.getMemberPrice() : goods.getBuyPrice();
            goods.setBuyPrice(buyPrice);
			IndexGoodsVO goodsCart = conversionIndexGoodsVO(goods);
			//获取自己点的菜、
			if (goods.getBuyerId().equals(buyerId) && !new Integer(1).equals(goods.getMustOrder())) {
				myGoodsList.add(goodsCart);
			//获取同桌点的菜
			} else if(!new Integer(1).equals(goods.getMustOrder())){
				otherGoodsList.add(goodsCart);
			}else{
				mustGoodsList.add(goodsCart);
			}

			double buyCount = goods.getBuyCount() == null ? 0.0 : goods.getBuyCount();
            Double originalBuyPrice = (!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice) ? goods.getMemberPrice() : goods.getOriginalPrice();

            //称重商品不计算价格
			if(!new Integer(1).equals(goods.getIsWeight())){
			    //如果为优惠商品回显前端计算 buyPrice,反之则为originalPrice
                oneGoodsPrice = Arith.mul(buyCount, Utils.isEmpty(goods.getCouponCode()) ? originalBuyPrice : buyPrice);
                totalBuyOriginalPrice = Arith.add(totalBuyOriginalPrice,oneGoodsPrice);
                totalPrice = Arith.add(totalPrice,Arith.mul(buyCount,buyPrice));
                totalOriginalPrice = Arith.add(totalOriginalPrice,Arith.mul(buyCount,goods.getOriginalPrice()));
            }
			// 获取自己点的菜品数量
			if (buyerId.equals(goods.getBuyerId())) {
				tableMyCount = Arith.add(tableMyCount, buyCount);
			} else {
				tableOtherCount = Arith.add(tableOtherCount, buyCount);
				//称重商品不计算价格
				if(!new Integer(1).equals(goods.getIsWeight())){
//                    double oneGoodsPrice = Arith.mul(goods.getBuyCount(), Utils.isEmpty(goods.getCouponCode()) ? goods.getOriginalPrice() : goods.getBuyPrice());
                    tableOtherPrice = Arith.add(tableOtherPrice, Arith.mul(goods.getBuyCount(),goods.getBuyPrice()));
                }
			}
			//获取相同商品添加不同属性的数量
			int goodsPropNum= 0;
//			if (!new Integer(2).equals(goods.getIsPackage())) {
//				GoodsCartExtend goodsCartExtendProp = new GoodsCartExtend();
//				goodsCartExtendProp.setStoreId(goods.getShopperId());
//				goodsCartExtendProp.setGoodsId(goods.getGoodsId());
//				goodsCartExtendProp.setStartDate(startDate);
//				goodsCartExtendProp.setEndDate(endDate);
//				goodsCartExtendProp.setPropIds(goods.getPropIds());
//				goodsCartExtendProp.setSizeId(goods.getSizeId());
//				goodsCartExtendProp.setBuyerId(buyerId);
//				if(StringUtils.isNotEmpty(goods.getTableNo())){
//					goodsCartExtendProp.setTableNo(goods.getTableNo());
//					goodsPropNum = goodsCartServiceApi.getSameGoodsDiffPropNumByTableNo(goodsCartExtendProp);
//				}else{
//					goodsPropNum = goodsCartServiceApi.getSameGoodsDiffPropNumByBuyerId(goodsCartExtendProp);
//				}
//			}
			goodsCart.setPropNums(goodsPropNum);
		}
		myGoods.put("goods", myGoodsList);
		otherGoods.put("goods", otherGoodsList);
		mustGoods.put("goods", mustGoodsList);

        Shopper shopper = shopperInfoServiceApi.getShopper(storeId);

        CouponBaseDto couponBaseDto = new CouponBaseDto();
        BeanUtils.copyProperties(shopCartIndexQueryVo,couponBaseDto);
        totalPrice = calcPromotionPriceByGoodsCart(totalPrice,goodsList, couponBaseDto, shopper, shopperConfigExt);

        IndexCartVO indexCart = new IndexCartVO();
		indexCart.setTotalPrice(totalPrice);
		indexCart.setTotalOriginalPrice(totalOriginalPrice);
		indexCart.setTotalBuyOriginalPrice(totalBuyOriginalPrice);

		indexCart.setMyGoods(myGoods);
		// 如果开启同桌单点不返回必须菜和同桌点的菜
		if (!StringUtils.isEmpty(tableName) && shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
			otherGoods.put("goods", new ArrayList<IndexGoodsVO>());
			mustGoods.put("goods", new ArrayList<IndexGoodsVO>());
			indexCart.setOtherGoods(otherGoods);
			indexCart.setMustGoods(mustGoods);
		} else {
			indexCart.setOtherGoods(otherGoods);
			indexCart.setMustGoods(mustGoods);
		}
		//获取清空时间 update by hyc 2019年4月16日15:23:00
		if(shopperConfigExt != null){
			indexCart.setClearCartTime(shopperConfigExt.getClearCartTime());
		}
		indexCart.setTableMyCount(tableMyCount);
		indexCart.setTableOtherPrice(tableOtherPrice);
		indexCart.setTableOtherCount(tableOtherCount);
		res.setData(indexCart);
		
		return res;
	}
	
	/**
	 * 转换GoodsCart
	 * 
	 * @param goods
	 * @param
	 * @return GoodsCartVO
	 * @author litao
	 * @date 2018年1月18日
	 */
	private IndexGoodsVO conversionIndexGoodsVO(GoodsCartAndDetail goods){
		IndexGoodsVO goodsCart = new IndexGoodsVO();
		goodsCart.setBuyCount(goods.getBuyCount());
		goodsCart.setBuyPrice(goods.getBuyPrice());
		goodsCart.setCategoryId(goods.getCategoryId());
		goodsCart.setCategoryName(goods.getCategoryName());
		goodsCart.setGoodsCartId(goods.getId());
		goodsCart.setGoodsId(goods.getGoodsId());
		goodsCart.setGoodsImg(goods.getGoodsImg());
		goodsCart.setGoodsName(goods.getGoodsName());
		goodsCart.setIsNotshowSize(goods.getIsNotshowSize());
		goodsCart.setIsPackage(goods.getIsPackage());
		goodsCart.setIsWeight(goods.getIsWeight());
		goodsCart.setPropIds(goods.getPropIds());
		goodsCart.setPropNames(goods.getPropNames());
		goodsCart.setPropPrice(goods.getPropPrice());
		goodsCart.setSizeId(goods.getSizeId());
		goodsCart.setSizeType(goods.getSizeType());
		goodsCart.setGoodsSellNum(goods.getMinSell()==null?1:goods.getMinSell());
		goodsCart.setGoodsAddNum(goods.getMinAddUnit()==null?1:goods.getMinAddUnit());
		goodsCart.setMustOrder(goods.getMustOrder());
		goodsCart.setMustOrderUpdate(goods.getMustOrderUpdate());
		goodsCart.setPropDetail(goods.getPropDetail());
        goodsCart.setCouponCode(goods.getCouponCode());
        goodsCart.setCouponCodeType(goods.getCouponCodeType());
        goodsCart.setCouponDetailCode(goods.getCouponDetailCode());
        goodsCart.setPromotionDesc(goods.getPromotionDesc());
        goodsCart.setMemberPrice(goods.getMemberPrice());
        goodsCart.setPromotionName(goods.getPromotionName());
        goodsCart.setOriginalPrice(goods.getOriginalPrice());

        List<GoodsCartItemVO> cartItems = null;
		//判断是否存在组合套餐商品信息
		if(!CollectionUtils.isEmpty(goods.getDetails())){
		    //套餐原价为计价后
//            double originalPrice = Utils.isEmpty(goods.getCouponCode()) ?  goods.getOriginalPrice()  : goods.getBuyPrice();
//            goodsCart.setOriginalPrice(originalPrice);
            cartItems = new ArrayList<GoodsCartItemVO>();
			List<GoodsCartDetail> goodsDetails = goods.getDetails();
			for(GoodsCartDetail details:goodsDetails){
				GoodsCartItemVO goodsCartItem = new GoodsCartItemVO();
				goodsCartItem.setBuyCount(details.getBuyCount());
				goodsCartItem.setBuyPrice(details.getBuyPrice());
				goodsCartItem.setCategoryId(details.getCategoryId());
				goodsCartItem.setCategoryName(details.getCategoryName());
				goodsCartItem.setGoodsCartId(details.getGoodsCartId());
				goodsCartItem.setGoodsGroupId(details.getGoodsGroupId());
				goodsCartItem.setGoodsGroupName(details.getGoodsGroupName());
				goodsCartItem.setGoodsId(details.getGoodsId());
				goodsCartItem.setGoodsImg(details.getGoodsImg());
				goodsCartItem.setGoodsName(details.getGoodsName());
				goodsCartItem.setId(details.getId());
				goodsCartItem.setIsNotshowSize(details.getIsNotshowSize());
				goodsCartItem.setIsRequre(details.getIsRequre());
				goodsCartItem.setOriginalPrice(details.getOriginalPrice());
				goodsCartItem.setPropIds(details.getPropIds());
				goodsCartItem.setPropNames(details.getPropNames());
				goodsCartItem.setPropPrice(details.getPropPrice());
				goodsCartItem.setSizeId(details.getSizeId());
				goodsCartItem.setSizeType(details.getSizeType());
				goodsCartItem.setSuitState(details.getSuitState());
				goodsCartItem.setPropDetail(details.getPropDetail());
				cartItems.add(goodsCartItem);
			}
		}
//		else{
//            //20200519 页面需求单品原价+加料加个
//            if(Utils.isEmpty(goodsCart.getCouponCode())){
//                double propPrice = goods.getPropPrice() == null ? 0D : goods.getPropPrice();
//                goodsCart.setOriginalPrice(Arith.add(propPrice, goods.getOriginalPrice()));
//            }else{
//                goodsCart.setOriginalPrice(goods.getBuyPrice());
//            }
//
//        }
		goodsCart.setDetails(cartItems);
		return goodsCart;
	}
	
	/**
	 * 转换GoodsCart
	 * 
	 * @param goods
	 * @param
	 * @return GoodsCartVO
	 * @author litao
	 * @date 2018年1月18日
	 */
	private GoodsCartVO conversionGoodsCartVO(GoodsCartAndDetail goods,Integer clientType){
		GoodsCartVO goodsCart = new GoodsCartVO();
		goodsCart.setBuyCount(goods.getBuyCount());
		goodsCart.setBuyPrice(goods.getBuyPrice());
		goodsCart.setCategoryId(goods.getCategoryId());
		goodsCart.setCategoryName(goods.getCategoryName());
		goodsCart.setGoodsCartId(goods.getId());
		goodsCart.setGoodsId(goods.getGoodsId());
		goodsCart.setGoodsImg(goods.getGoodsImg());
		goodsCart.setGoodsName(goods.getGoodsName());
		goodsCart.setIsNotshowSize(goods.getIsNotshowSize());
		goodsCart.setIsPackage(goods.getIsPackage());
		goodsCart.setIsWeight(goods.getIsWeight());
		goodsCart.setPropIds(goods.getPropIds());
		goodsCart.setPropNames(goods.getPropNames());
		goodsCart.setPropPrice(goods.getPropPrice());
		goodsCart.setSizeId(goods.getSizeId());
		goodsCart.setSizeType(goods.getSizeType());
		goodsCart.setGoodsDesc(goods.getGoodsDesc());
		goodsCart.setRemark(goods.getRemark());
		goodsCart.setGoodsAddNum(goods.getMinAddUnit()==null?1:goods.getMinAddUnit());
		goodsCart.setGoodsSellNum(goods.getMinSell()==null?1:goods.getMinSell());
		goodsCart.setMustOrder(goods.getMustOrder());
		goodsCart.setMustOrderUpdate(goods.getMustOrderUpdate());
		goodsCart.setPropDetail(goods.getPropDetail());
		goodsCart.setMemberPrice(goods.getMemberPrice());
        goodsCart.setCouponCode(goods.getCouponCode());
        goodsCart.setCouponCodeType(goods.getCouponCodeType());
        goodsCart.setCouponDetailCode(goods.getCouponDetailCode());
        goodsCart.setPromotionDesc(goods.getPromotionDesc());
        goodsCart.setPromotionName(goods.getPromotionName());
        goodsCart.setOriginalPrice(goods.getOriginalPrice());

        DiscountInfoVO discountInfoVO = null;
		if(!Utils.isEmpty(goods.getDiscountItemId()) && new Integer(3).equals(clientType)){
			discountInfoVO = new DiscountInfoVO();
			discountInfoVO.setItemId(goods.getDiscountItemId());
			discountInfoVO.setItemType(goods.getItemType());
			discountInfoVO.setIsSingleDiscount(goods.getIsSingleDiscount());
			discountInfoVO.setDiscountInfo(goods.getDiscountRate()==null?null:String.valueOf(goods.getDiscountRate()));
		}
		goodsCart.setDiscountInfo(discountInfoVO);
		
		List<GoodsCartItemVO> cartItems = null;
		//判断是否存在组合套餐商品信息
		if(!CollectionUtils.isEmpty(goods.getDetails())){
            //套餐原价为计价后
//            double originalPrice = Utils.isEmpty(goods.getCouponCode()) ?  goods.getOriginalPrice()  : goods.getBuyPrice();
//            goodsCart.setOriginalPrice(originalPrice);
			cartItems = new ArrayList<GoodsCartItemVO>();
			List<GoodsCartDetail> goodsDetails = goods.getDetails();
			for(GoodsCartDetail details:goodsDetails){
				GoodsCartItemVO goodsCartItem = new GoodsCartItemVO();
				goodsCartItem.setBuyCount(details.getBuyCount());
				goodsCartItem.setBuyPrice(details.getBuyPrice());
				goodsCartItem.setCategoryId(details.getCategoryId());
				goodsCartItem.setCategoryName(details.getCategoryName());
				goodsCartItem.setGoodsCartId(details.getGoodsCartId());
				goodsCartItem.setGoodsGroupId(details.getGoodsGroupId());
				goodsCartItem.setGoodsGroupName(details.getGoodsGroupName());
				goodsCartItem.setGoodsId(details.getGoodsId());
				goodsCartItem.setGoodsImg(details.getGoodsImg());
				goodsCartItem.setGoodsName(details.getGoodsName());
				goodsCartItem.setId(details.getId());
				goodsCartItem.setIsNotshowSize(details.getIsNotshowSize());
				goodsCartItem.setIsRequre(details.getIsRequre());
				goodsCartItem.setOriginalPrice(details.getOriginalPrice());
				goodsCartItem.setPropIds(details.getPropIds());
				goodsCartItem.setPropNames(details.getPropNames());
				goodsCartItem.setPropPrice(details.getPropPrice());
				goodsCartItem.setSizeId(details.getSizeId());
				goodsCartItem.setSizeType(details.getSizeType());
				goodsCartItem.setSuitState(details.getSuitState());
				goodsCartItem.setPropDetail(details.getPropDetail());
				cartItems.add(goodsCartItem);
			}
		}
//		else{
//            //20200519 页面需求单品原价+加料加个
//            if(Utils.isEmpty(goodsCart.getCouponCode())){
//                double propPrice = goods.getPropPrice() == null ? 0D : goods.getPropPrice();
//                goodsCart.setOriginalPrice(Arith.add(propPrice, goods.getOriginalPrice()));
//            }else{
//                goodsCart.setOriginalPrice(goods.getBuyPrice());
//            }
//        }
		goodsCart.setDetails(cartItems);
		return goodsCart;
	}
	
	@Override
	public CoreResponse<ShopCartVO> getShopCartbyPage(ShopCartPageQueryDto shopCartPageQueryVo, Integer clientType){

		CoreResponse<ShopCartVO> res = new CoreResponse<ShopCartVO>();
        Integer storeId = shopCartPageQueryVo.getStoreId();
        String tableName = shopCartPageQueryVo.getTableName();
        String buyerId = shopCartPageQueryVo.getBuyerId();
        Integer clientOrderMode = shopCartPageQueryVo.getClientOrderMode();
        Integer isOut = shopCartPageQueryVo.getIsOut();

        String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		List<GoodsCartAndDetail> goodsList = null;
		// 获取redis店铺配置信息
		Object config = redisService.getObj(storeId + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(storeId);
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		// 获取购物车商品信息
		if (!StringUtils.isEmpty(tableName)) {
			if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
				// 如果开启同桌单点就根据桌台和顾客Id查询
				goodsList = goodsCartServiceApi.getGoodsCartByTableNoAndBuyerId(storeId, tableName, startDate, endDate, buyerId);
			} else {
				// 根据桌台查询
				goodsList = goodsCartServiceApi.getGoodsCartByTableNo(storeId, tableName, startDate, endDate,clientOrderMode);
			}
		} else {
			// 根据顾客Id查询
			goodsList = goodsCartServiceApi.getGoodsCartByBuyerId(storeId, buyerId, startDate, endDate,clientOrderMode);
		}
		
		if (CollectionUtils.isEmpty(goodsList)) {
			res.setData(null);
			res.setMsg("购物车暂无数据");
			return res;
		}
		ShopCartVO shopCart = new ShopCartVO();
		
		Map<Long, CategoryShopCartVO> shopCartMap = new HashMap<Long, CategoryShopCartVO>();
		Map<String, CategoryShopCartBuyIdVO> goodsCartMap = new HashMap<String, CategoryShopCartBuyIdVO>();

		List<CategoryShopCartVO> categoryShopCart = new ArrayList<CategoryShopCartVO>();
		List<GoodsCartVO> mustGoods = new ArrayList<GoodsCartVO>();
		// 所有商品总价
		Double totalPrice = 0.0;
		double totalOriginalPrice = 0D;
		double oneGoodsPrice = 0D;
		double totalBuyCount = 0.0;
		double totalBuyOriginalPrice = 0D;
		int itemCount = 0;
        //是否享受会员价
        boolean isEnjoyMemberPrice = indexService.isEnjoyMemberPrice(shopCartPageQueryVo, shopperConfigExt);

		for (GoodsCartAndDetail goods : goodsList) {
            //20200612会员价回显
            Double buyPrice = !Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice ? goods.getMemberPrice() : goods.getBuyPrice();
            goods.setBuyPrice(buyPrice);
			GoodsCartVO goodsCart= conversionGoodsCartVO(goods,clientType);
			//必点菜商品
			if(new Integer(1).equals(goods.getMustOrder())){
				mustGoods.add(goodsCart);
			}else{
				// 组装商品分类
				CategoryShopCartVO goodsVO = shopCartMap.get(goods.getCategoryId());
				if (goodsVO == null) {
					// 没有分类就新建分类
					goodsVO = new CategoryShopCartVO();
					goodsVO.setCategoryId(goods.getCategoryId());
					goodsVO.setCategoryName(goods.getCategoryName());
					shopCartMap.put(goodsVO.getCategoryId(), goodsVO);
					// 把分类添加到分类集合
					categoryShopCart.add(goodsVO);
				}
				// 组装购买者商品 （每个分类的购买者）
				CategoryShopCartBuyIdVO goodsObj = goodsCartMap.get(goods.getCategoryId() + goods.getBuyerId());
				if (goodsObj == null) {
					goodsObj = new CategoryShopCartBuyIdVO();
					goodsObj.setBuyerId(goods.getBuyerId());
					goodsObj.setAvatarPath(goods.getAvatarPath());
					goodsObj.setBuyNick(goods.getBuyNick());
					goodsObj.setBuyerCount(goods.getBuyCount());
					// 添加商品到临时变量里面去
					goodsCartMap.put(goods.getCategoryId() + goodsObj.getBuyerId(), goodsObj);
					// 添加商品到分类里面去
					goodsVO.getCategoryGoods().add(goodsObj);
				}else{
					goodsObj.setBuyerCount(Arith.add(goodsObj.getBuyerCount(),goods.getBuyCount()));	
				}										
				// 计算分类下菜品数量
				goodsVO.setCategoryCount(Arith.add(goodsVO.getCategoryCount(), goods.getBuyCount()));
				
				goodsObj.getGoods().add(goodsCart);
			}
			// 计算优惠菜品数量
			if (!StringUtils.isEmpty(goods.getItemType())) {
				itemCount++;
			}
			// 计算总的购买数量
			totalBuyCount = Arith.add(totalBuyCount, goods.getBuyCount());
            Double originalBuyPrice = (!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice) ? goods.getMemberPrice() : goods.getOriginalPrice();

            // 计算一个商品的价格
			if(!new Integer(1).equals(goods.getIsWeight())){
				// 计算总价
				totalPrice = Arith.add(Arith.mul(goods.getBuyCount(), buyPrice), totalPrice);
				//原价总价
                totalOriginalPrice = Arith.add(Arith.mul(goods.getBuyCount(), goodsCart.getOriginalPrice()),totalOriginalPrice);
                //原购买总价（方便页面计算）
                oneGoodsPrice = Arith.mul(goods.getBuyCount(), Utils.isEmpty(goods.getCouponCode()) ? originalBuyPrice : buyPrice);
                totalBuyOriginalPrice = Arith.add(oneGoodsPrice,totalBuyOriginalPrice);
			}
		}

        Shopper shopper = shopperInfoServiceApi.getShopper(storeId);

        CouponBaseDto couponBaseDto = new CouponBaseDto();
        BeanUtils.copyProperties(shopCartPageQueryVo,couponBaseDto);
        totalPrice = calcPromotionPriceByGoodsCart(totalPrice,goodsList, couponBaseDto, shopper,shopperConfigExt);

        //餐具费
//		ShopperConfig boxConfig= shopperInfoServiceApi.getShopperConfig(storeId, "CTR_BOX_PRICE");
//		Double boxPrice = (boxConfig==null || boxConfig.getPropValue()==null)?0d:Double.valueOf(boxConfig.getPropValue());
//		if (peopleNum != null && peopleNum > 0 && boxPrice > 0) {
//			totalPrice = Arith.add(totalPrice, Arith.mul(peopleNum, boxPrice));
//		}
		//在线订单不需要在购物车中计算打包费
		if(!Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue().equals(clientOrderMode)){
			// 打包费
			Double bagPrice = 0.0d;
			Integer koubeiDinner = 0;
			if(shopperConfigExt!=null){
				bagPrice = shopperConfigExt.getBagPrice();
				koubeiDinner = shopperConfigExt.getKoubeiDinner();
			}
			// 口碑正餐后付不计算餐具费、打包费
			if(!new Integer(1).equals(koubeiDinner)){
				// 获取商品打包费
				Double goodsBagPrice = computeGoodsPrice(bagPrice,isOut,totalBuyCount, goodsList);
				totalPrice = Arith.add(totalPrice, goodsBagPrice);
                totalOriginalPrice = Arith.add(totalOriginalPrice, goodsBagPrice);
			}
			// 默认显示打包
			shopCart.setShowBag(0);
			
			// 查询进行中订单状态
			Waimai waimai = waimaiOrderService.getMyOrderStatus(storeId, tableName, buyerId,null);
			if(waimai!=null && new Integer(0).equals(waimai.getPayStatus())){
				shopCart.setShowBag(new Integer(1).equals(waimai.getIsOut()) ? 2 : 1);
				shopCart.setPeopleNumber(waimai.getPeopleNumber());
			}
		}else{
			// 在线订单 不显示整单打包及单个打包标签
			shopCart.setShowBag(2);
			Object peopleNumber = redisService.getObj(storeId+"_"+buyerId+"_peopleNumber");
			if(peopleNumber!=null && StringUtils.isNotEmpty(String.valueOf(peopleNumber))){
				shopCart.setPeopleNumber(Integer.valueOf(String.valueOf(peopleNumber)));
			}
		}
		//获取清空时间 update by hyc 2019年4月16日15:23:00
		if(shopperConfigExt != null){
			shopCart.setClearCartTime(shopperConfigExt.getClearCartTime());
		}
        shopCart.setTotalOriginalPrice(totalOriginalPrice);
        shopCart.setTotalPrice(totalPrice);
        shopCart.setTotalBuyOriginalPrice(totalBuyOriginalPrice);
		shopCart.setItemCount(itemCount);
		shopCart.setGoodsCount(goodsList.size());
		shopCart.setGoodsTotalCount(totalBuyCount);
		shopCart.setCategoryShopCart(categoryShopCart);
		shopCart.setMustGoods(mustGoods);
		res.setData(shopCart);
		return res;
	}

	//20200508 计算优惠金额 预咨询接口 有全场券计算券优惠、没有券计算商家活动优惠、商家
    @Override
    public Double calcPromotionPriceByGoodsCart(Double totalPrice, List<GoodsCartAndDetail> goodsList, CouponBaseDto couponBaseDto, Shopper shopper,ShopperConfigExtend shopperConfigExtend){
        List<Map<String,Object>> itemList = new LinkedList<>();
        String memberId = couponBaseDto.getMemberId();
        Object vouchers = couponBaseDto.getVouchers();
        Integer isVip = Optional.ofNullable(couponBaseDto.getIsVip()).orElse(0);
        //是否享用会员价
        boolean isEnjoyMemberPrice = indexService.isEnjoyMemberPrice(couponBaseDto, shopperConfigExtend);
        for (GoodsCartAndDetail goods: goodsList){
            HashMap<String, Object> itemMap = new HashMap<>();
            itemMap.put("buy_count",goods.getBuyCount());
            //20200603会员价计算
            logger.info("CART 计算 = "+goods.getMemberPrice() + ",memberId="+memberId);
            itemMap.put("buy_price",!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice ? goods.getMemberPrice() :goods.getBuyPrice());
            itemMap.put("goods_id",goods.getGoodsId());
            itemMap.put("goods_name",goods.getGoodsName());
            itemMap.put("item_guid",new Date().getTime());//
            //20200507 smo单品已优惠、方便预咨询计算全场
            itemMap.put("original_price",!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice ? goods.getMemberPrice() :goods.getBuyPrice());
            itemMap.put("is_member_price",!Utils.isEmpty(goods.getMemberPrice()) && isEnjoyMemberPrice ? 1 : 0);
            itemMap.put("size_id",goods.getSizeId());
            itemMap.put("coupon_code",goods.getCouponCode());
            itemList.add(itemMap);
        }
        List<Map<String,Object>> vouchersListParam = new LinkedList<>();
        if(!Utils.isEmpty(vouchers)){
            if(vouchers instanceof String){
                String vouchersStr = (String)vouchers;
                for (String voucherUid : vouchersStr.split(",")) {
                    Map<String, Object> vouchersMap = new LinkedHashMap<>();
                    vouchersMap.put("uuid",voucherUid);
                    vouchersListParam.add(vouchersMap);
                }
            }else if(vouchers instanceof List){
                List vouchersList = (List)vouchers;
                for (Object voucherUid : vouchersList) {
                    Map<String, Object> vouchersMap = new LinkedHashMap<>();
                    vouchersMap.put("uuid",voucherUid);
                    vouchersListParam.add(vouchersMap);
                }
            }

        }

        HashMap<String, Object> user = new HashMap<>();
        user.put("user_id",memberId);

        JSONObject paramsJson = new JSONObject();
        paramsJson.put("invoke_source","1802");
        paramsJson.put("item",itemList);
        paramsJson.put("is_pay_member",isVip);
//        paramsJson.put("order",orderMap);
        paramsJson.put("user",user);
        paramsJson.put("request_no",Utils.createOrderNum(shopper.getId()));
        paramsJson.put("store_id",shopper.getId());
        paramsJson.put("shop_id",shopper.getParentId());
        paramsJson.put("order",new Object());
        paramsJson.put("is_from_cart","1");
        //优惠券信息
        paramsJson.put("voucher",vouchersListParam);
        logger.info("优惠券预咨询请求参数："+paramsJson.toJSONString());
        long start = System.currentTimeMillis();
        String resultString = HttpUtil.doPost(marketingUrl+"/promotion/consult", paramsJson);
        logger.info("预咨询请求耗时：" + (System.currentTimeMillis() - start));
        String responseLogJsonString = null;
        if(resultString != null){
            JSONObject resultJson = JSONObject.parseObject(resultString);
            if("10000".equals(resultJson.getString("code"))){
                JSONObject dataJson = resultJson.getJSONObject("data");
                //计算后总价
                String total_price = dataJson.getString("total_price");
                if(total_price != null){
                    totalPrice = Double.valueOf(total_price);
                }
                JSONObject responseLogJson = new JSONObject();
                responseLogJson.putAll(resultJson);
                //日志打印，voucher_list实在太多
                responseLogJson.getJSONObject("data").remove("voucher_list");
                responseLogJsonString = responseLogJson.toJSONString();
            }else {
                responseLogJsonString = resultString;
            }
        }
        logger.info("优惠券预咨询返回参数："+responseLogJsonString);
	    return totalPrice;
    }


    /**
	 * 计算商品打包费用
	 * 
	 * @param @return
	 * @return Double
	 * @throws @author
	 *             litao
	 * @date 2018年1月2日
	 */
	private Double computeGoodsPrice(Double bagPrice,Integer isOut, Double totalBuyCount, List<GoodsCartAndDetail> goodsList) {
		Double packBuyCount = 0.0;
		Double packBuyPrice = 0.0;
		// 计算打包费
		if (bagPrice > 0 && !new Integer(1).equals(isOut)) {
			for (GoodsCartAndDetail goods : goodsList) {
				if ("打包".equals(goods.getGoodsDesc())) {
					packBuyCount = Arith.add(packBuyCount, goods.getBuyCount());
				}
			}
			packBuyPrice = Arith.mul(bagPrice,packBuyCount);
		}
		if (isOut == 1 && bagPrice > 0) {
			packBuyPrice = Arith.mul(bagPrice, totalBuyCount);
		}
		return packBuyPrice;
	}

	@Override
	public CoreResponse<StatusInfo> updateShopCartProp(ShopCartPropEntryVO shopCartProp) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		//查询该商品是否存在
		GoodsCartAndDetail goodsCartDetail = goodsCartServiceApi.getGoodsCartById(shopCartProp.getGoodsCartId());
		if (goodsCartDetail == null) {
			res.setStatusInfo(StatusInfo.NORESOURCE);
			res.setMsg("该商品已被同桌删除");
			return res;
		}
		GoodsCartExtend goodsCartExtend = new GoodsCartExtend();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		goodsCartExtend.setStoreId(shopCartProp.getStoreId());
		goodsCartExtend.setBuyerId(shopCartProp.getBuyerId());
		goodsCartExtend.setGoodsId(shopCartProp.getGoodsId());
		goodsCartExtend.setSizeId(shopCartProp.getSizeId());
		goodsCartExtend.setIsPackage(shopCartProp.getIsPackage());
		goodsCartExtend.setPropIds(shopCartProp.getPropIds());
		goodsCartExtend.setStartDate(startDate);
		goodsCartExtend.setEndDate(endDate);
		goodsCartExtend.setGoodsDesc(goodsCartDetail.getGoodsDesc());
		//查询购物车是否存在相同的商品属性
		GoodsCart goodsCart= goodsCartServiceApi.getGoodsCartByRemarkCommit(goodsCartExtend);
		GoodsCart cart = new GoodsCart();
		//如果存在相同的商品属性则删除现在的商品，修改相同商品的数量
		if(goodsCart!=null){
			cart.setBuyCount(Arith.add(goodsCart.getBuyCount(),goodsCartDetail.getBuyCount()));
			cart.setId(goodsCart.getId());
			cart.setCreateTime(new Date());
			goodsCartServiceApi.updateGoodsCart(goodsCart);
			if(!goodsCart.getId().equals(shopCartProp.getGoodsCartId())){
				goodsCartServiceApi.deleteGoodsCartById(shopCartProp.getGoodsCartId());
			}
		//如果不存在相同的商品属性则直接修改该商品的属性即可
		}else{
			cart.setPropIds(shopCartProp.getPropIds());
			cart.setPropNames(shopCartProp.getPropNames());
			cart.setBuyCount(goodsCartDetail.getBuyCount());
			cart.setRemark(shopCartProp.getRemark());
			cart.setId(shopCartProp.getGoodsCartId());
			cart.setPropDetail(goodsCartDetail.getPropDetail());
			goodsCartServiceApi.updateGoodsCart(cart);
		}
		return res;
	}

	@Override
	public CoreResponse<StatusInfo> updateOrDeleteShopCartById(UpdateCartEntryVO goodsCart) {
		CoreResponse<StatusInfo> res = new CoreResponse<StatusInfo>();
		GoodsCart cart = new GoodsCart();
		if (goodsCart.getBuyCount() >= 1) {
			cart.setId(goodsCart.getGoodsCartId());
			cart.setBuyCount(goodsCart.getBuyCount());
			goodsCartServiceApi.updateGoodsCart(cart);
			res.setMsg("更新购物成功");
		} else if (goodsCart.getBuyCount() == 0) {
			//必选菜删除只修改mustOrderUpdate状态为-1，实际数据不删除
			if(new Integer(1).equals(goodsCart.getMustOrder())){
				cart.setId(goodsCart.getGoodsCartId());
				cart.setBuyCount(goodsCart.getBuyCount());
				cart.setMustOrderUpdate(-1);
				goodsCartServiceApi.updateGoodsCart(cart);
			}else{
				goodsCartServiceApi.deleteGoodsCartById(goodsCart.getGoodsCartId());
			}
			res.setMsg("删除商品成功");
		}
		return res;
	}

	@Override
	public CoreResponse<SaveShopCartVO> saveOrUpdateShopCartV2(SaveShopCartEntryVO goodsCartVO) {
		//logger.info("SaveShopCartEntryVO:"+JSONObject.toJSONString(goodsCartVO));
		GoodsCart goodsCart = null;
		CoreResponse<SaveShopCartVO> res = new CoreResponse<SaveShopCartVO>();
		SaveShopCartVO saveCart = new SaveShopCartVO();
		String startDate = DateUtils.getYesterdayStartTime();
		String endDate = DateUtils.getTodayEndTime();
		String buyerId = goodsCartVO.getUserInfo().getBuyerId();
		// 获取redis店铺白名单配置信息
		Object shopperWhite = redisService.getObj(goodsCartVO.getStoreId() + "_shopperWhite");
		if(shopperWhite!=null){
			Map<String,Integer> whiteMap = (HashMap<String, Integer>)shopperWhite;
			//判断存在有属性的商品加入购物车，校验加料信息
			if(whiteMap!=null && new Integer(1).equals(whiteMap.get("checkGoodsProp"))){
				if (new Integer(0).equals(goodsCartVO.getIsPackage())
						&& Arith.sub(goodsCartVO.getBuyPrice(), goodsCartVO.getOriginalPrice()) > 0
						&& (StringUtils.isEmpty(goodsCartVO.getPropIds())
								|| StringUtils.isEmpty(goodsCartVO.getPropNames()))) {
					saveCart.setSuccess(false);
					res.setData(saveCart);
					res.setMsg("添加购物车失败,加料商品添加有误");
					return res;
				}
			}
		}
		//判断是否存在已有相同商品属性，组合套餐不查询
		if (!new Integer(2).equals(goodsCartVO.getIsPackage())) {
			GoodsCartExtend goodsCartExtend = new GoodsCartExtend();
			goodsCartExtend.setStoreId(goodsCartVO.getStoreId());
			goodsCartExtend.setGoodsId(goodsCartVO.getGoodsId());
			goodsCartExtend.setStartDate(startDate);
			goodsCartExtend.setEndDate(endDate);
			goodsCartExtend.setPropIds(goodsCartVO.getPropIds());
			goodsCartExtend.setSizeId(goodsCartVO.getSizeId());
			goodsCartExtend.setGoodsDesc(goodsCartVO.getGoodsDesc());
			goodsCartExtend.setBuyerId(buyerId);
			goodsCartExtend.setPropDetail(goodsCartVO.getPropDetail());
            goodsCartExtend.setCouponCode(goodsCartVO.getCouponCode());
			if (StringUtils.isNotEmpty(goodsCartVO.getTableNo())) {
				goodsCartExtend.setTableNo(goodsCartVO.getTableNo());
				goodsCart = goodsCartServiceApi.getSamePropGoodsByTableNo(goodsCartExtend);
			} else {
				goodsCart = goodsCartServiceApi.getSamePropGoodsByBuyerId(goodsCartExtend);
			}
		}
		//加入购物车
		if (goodsCart == null) {
			GoodsCartAndDetail goodsCartAndDetail = new GoodsCartAndDetail();
			BeanUtils.copyProperties(goodsCartVO, goodsCartAndDetail);
			//logger.info("goodsCartAndDetail:"+JSONObject.toJSONString(goodsCartAndDetail));
			//set用户信息
			goodsCartAndDetail.setBuyerId(buyerId);
			goodsCartAndDetail.setShopperId(goodsCartVO.getStoreId());
			goodsCartAndDetail.setBuyNick(goodsCartVO.getUserInfo().getBuyNick());
			goodsCartAndDetail.setAvatarPath(goodsCartVO.getUserInfo().getAvatarPath()==null?"":goodsCartVO.getUserInfo().getAvatarPath());
			goodsCartAndDetail.setGoodsImg(goodsCartVO.getImagePath());
			goodsCartAndDetail.setIsNotshowSize(goodsCartVO.getSizeCount()>=2?0:1); //0显示规格 ，1不显示规格
			goodsCartAndDetail.setMinSell(goodsCartVO.getGoodsSellNum());
			goodsCartAndDetail.setMinAddUnit(goodsCartVO.getGoodsAddNum());
			if(Utils.isEmpty(goodsCartVO.getCouponCode())){
                goodsCartAndDetail.setCouponCodeType(2);//优惠类型 2：smo
            }
			//set商品折扣信息
			if (goodsCartVO.getDiscountInfo() != null) {
				goodsCartAndDetail.setItemType(goodsCartVO.getDiscountInfo().getItemType());
				goodsCartAndDetail.setDiscountItemId(goodsCartVO.getDiscountInfo().getItemId());
				goodsCartAndDetail
						.setDiscountRate(Double.valueOf(goodsCartVO.getDiscountInfo().getDiscountInfo() == null ? "0"
								: goodsCartVO.getDiscountInfo().getDiscountInfo()));
				goodsCartAndDetail.setIsSingleDiscount(goodsCartVO.getDiscountInfo().getIsSingleDiscount());
			}
			goodsCartAndDetail.setCreateTime(new Date());
			//如果是组合套餐则需要添加明细
			if (!CollectionUtils.isEmpty(goodsCartVO.getDetails())
					&& new Integer(2).equals(goodsCartVO.getIsPackage())) {
				List<GoodsCartItemVO> goodsCartItemVO = goodsCartVO.getDetails();
				for (GoodsCartItemVO goodsDetail : goodsCartItemVO) {
					BeanUtils.copyProperties(goodsDetail, goodsCartAndDetail.getDetails());
				}
				
			}
			int gcId = goodsCartServiceApi.saveGoodsCart(goodsCartAndDetail);
			saveCart.setGoodsCartId(gcId);
		//存在相同的商品则直接修改数量
		} else {
			//称重商品只能添加一次
			if(goodsCart.getIsWeight()!=1){
				goodsCart.setBuyCount(Arith.add(goodsCart.getBuyCount(), goodsCartVO.getBuyCount()));
				goodsCartServiceApi.updateGoodsCart(goodsCart);
			}
			saveCart.setGoodsCartId(goodsCart.getId());
		}
		//获取相同商品添加不同属性的数量
		int goodsPropNum= 0;
//		if (!new Integer(2).equals(goodsCartVO.getIsPackage())) {
//			GoodsCartExtend goodsCartExtendProp = new GoodsCartExtend();
//			goodsCartExtendProp.setStoreId(goodsCartVO.getStoreId());
//			goodsCartExtendProp.setGoodsId(goodsCartVO.getGoodsId());
//			goodsCartExtendProp.setStartDate(startDate);
//			goodsCartExtendProp.setEndDate(endDate);
//			goodsCartExtendProp.setPropIds(goodsCartVO.getPropIds());
//			goodsCartExtendProp.setSizeId(goodsCartVO.getSizeId());
//			goodsCartExtendProp.setBuyerId(buyerId);
//			if(StringUtils.isNotEmpty(goodsCartVO.getTableNo())){
//				goodsCartExtendProp.setTableNo(goodsCartVO.getTableNo());
//				goodsPropNum = goodsCartServiceApi.getSameGoodsDiffPropNumByTableNo(goodsCartExtendProp);
//			}else{
//				goodsPropNum = goodsCartServiceApi.getSameGoodsDiffPropNumByBuyerId(goodsCartExtendProp);
//			}
//		}
//		map.put("goodsPropNum", goodsPropNum);
		saveCart.setGoodsPropNum(goodsPropNum);
		saveCart.setSuccess(true);
		res.setData(saveCart);
		res.setMsg("添加成功");
		return res;
	}

	@Override
	public CoreResponse<Map<String,Object>> updateSinglePackGoods(SinglePackEntryVO singlePackEntry) {
		CoreResponse<Map<String,Object>> res =new CoreResponse<Map<String,Object>>();
		//需要打包的商品个数
		Double packCount = singlePackEntry.getPackCount();
		Map<String,Object> packMap = new HashMap<String,Object>(); 
		GoodsCartAndDetail goodsCart = getShopCartById(singlePackEntry.getGoodsCartId());
		if(goodsCart==null){
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("打包失败，同桌已下单或者删除了该菜品");
			return res;
		}
		//商品的总数量
		Double goodsCountTotal = goodsCart.getBuyCount();
		packMap.put("isOut", new Integer(0));
		if (goodsCart.getGoodsDesc().contains("打包")) {
			res.setMsg("打包成功");
			res.setData(packMap);
			return res;
		}
		//如果为组合套餐则直接打包所有份数（不存在拆分及合并打包）
		if (new Integer(2).equals(goodsCart.getIsPackage())) {
			GoodsCart updateCart = new GoodsCart();
			updateCart.setGoodsDesc("打包");
			updateCart.setId(goodsCart.getId());
			updateCart.setBuyCount(goodsCart.getBuyCount());
			updateGoodsCartById(updateCart);
		}else{
			GoodsCartExtend goods = new GoodsCartExtend();
			goods.setStoreId(goodsCart.getShopperId());
			goods.setGoodsId(goodsCart.getGoodsId());
			goods.setBuyerId(goodsCart.getBuyerId());
			goods.setTableNo(goodsCart.getTableNo());
			goods.setSizeId(goodsCart.getSizeId());
			goods.setPropIds(goodsCart.getPropIds());
			goods.setGoodsDesc("打包");
			//查询是否有相同的商品已经打包了数量
			Integer count = getShopCartByPack(goods);
			if(count>=1){
				deleteShopCartByPack(goods);
			}
			GoodsCart cart = new GoodsCart();
			cart.setBuyCount(Arith.add(goodsCart.getBuyCount(), (double)count));
			// 所选商品是全部打包
			if (Arith.sub(goodsCart.getBuyCount(), packCount) == 0) {
				cart.setGoodsDesc("打包");
				cart.setId(goodsCart.getId());
				if(count>=1){
					cart.setBuyCount(Arith.add(goodsCart.getBuyCount(),Double.valueOf(count)));
				}else{
					cart.setBuyCount(goodsCart.getBuyCount());
				}
				updateGoodsCartById(cart);
			} else {
				// 修改原始该商品信息的份数及打包标记
				cart.setGoodsDesc("打包");
				cart.setBuyCount(Arith.add(packCount, (double)count));
				cart.setId(goodsCart.getId());
				Integer updateCount = updateGoodsCartById(cart);
				if (updateCount > 0 && Arith.sub(goodsCart.getBuyCount(), packCount) > 0) {
					// 往购物车里插入一条不打包的商品信息
					goodsCart.setGoodsDesc("");
					goodsCart.setBuyCount(Arith.sub(goodsCart.getBuyCount(), packCount));
					goodsCart.setId(null);
					int gcId = goodsCartServiceApi.saveGoodsCart(goodsCart);
//					Map<String,Integer> cartMap= saveOrUpdateShopCartV2(goodsCart);
//					Integer gcId = null;
//					if(cartMap!=null){
//						gcId = cartMap.get("gcId");
//					}
//					packMap.put("goodsCartId", gcId);
				}
			}
		}
		if (Arith.sub(goodsCountTotal, packCount) == 0) {
			// 店铺Id
			Integer storeId = singlePackEntry.getStoreId();
			// 桌台名称
			String tableName = singlePackEntry.getTableName();
			// 顾客Id
			String buyerId = singlePackEntry.getBuyerId();
			// 如果购物车里所有商品都是打包，则为整单打包
			Waimai order = null;
			if(!StringUtils.isEmpty(tableName)){
				order = waimaiOrderService.getMyOrderStatus(storeId, tableName, buyerId,null);
			}
			// 获取店铺配置
			ShopperConfigExtend  shopperConfig = null;
			Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(storeId);
			shopperConfig= SweepOrderUtils.convertToShopperConfigVO(configMap);
			if (null == order || new Integer(1).equals(order.getPayStatus())) {
				List<GoodsCartAndDetail> goodsList = getShopCart(storeId, tableName, buyerId,singlePackEntry.getClientOrderMode(), shopperConfig.getFirstPayMent(), shopperConfig.getIsOpenDeskmateSinglePoint());
				boolean flagCar = true;
				if (!CollectionUtils.isEmpty(goodsList)) {
					for (GoodsCartAndDetail good : goodsList) {
						if (good.getGoodsDesc() != null && !good.getGoodsDesc().contains("打包")) {
							flagCar = false;
							break;
						}
					}
				}
				if (flagCar) {
					String goodsDesc = "";
					updateGoodsCartByGoodsDesc(storeId, tableName, buyerId, goodsDesc);
					packMap.put("isOut", new Integer(1));
				}
			}
		}
		res.setMsg("打包成功");
		res.setData(packMap);
		return res;
	}

	@Override
	public CoreResponse<Map<String, Integer>> updateAllPackGoods(AllPackEntryVO allPackEntry) {
		CoreResponse<Map<String, Integer>> res = new CoreResponse<Map<String, Integer>>();
		// 店铺id
		Integer storeId = allPackEntry.getStoreId();
		// 桌台名称
		String tableName = allPackEntry.getTableName();
		// 顾客Id
		String buyerId = allPackEntry.getBuyerId();
		// 获取店铺配置
		ShopperConfigExtend  shopperConfig = null;
		Map<String, Object> configMap = shopperInfoServiceApi.getShopperAllConfig(storeId);
		shopperConfig= SweepOrderUtils.convertToShopperConfigVO(configMap);
		Map<String, Integer> isOutMap = new HashMap<String, Integer>();
		List<GoodsCartAndDetail> goodsCartList = getShopCart(storeId, tableName, buyerId,allPackEntry.getClientOrderMode(), shopperConfig.getFirstPayMent(), shopperConfig.getIsOpenDeskmateSinglePoint());
		if (CollectionUtils.isEmpty(goodsCartList)) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("整单打包失败，购物车暂无数据");
			return res;
		}
		
		//合并取消打包项
		for(GoodsCartAndDetail goodsCart:goodsCartList){
			if(goodsCart.getGoodsDesc()!=null && goodsCart.getGoodsDesc().contains("打包")){
				GoodsCartExtend goodsCartExtend = new GoodsCartExtend();
				goodsCartExtend.setStoreId(goodsCart.getShopperId());
				goodsCartExtend.setGoodsId(goodsCart.getGoodsId());
				goodsCartExtend.setStartDate(DateUtils.getYesterdayStartTime());
				goodsCartExtend.setEndDate(DateUtils.getTodayEndTime());
				goodsCartExtend.setPropIds(goodsCart.getPropIds());
				goodsCartExtend.setSizeId(goodsCart.getSizeId());
				goodsCartExtend.setBuyerId(goodsCart.getBuyerId());
				goodsCartExtend.setGoodsDesc("");
				GoodsCart cart = null;
				//查询是否有相同的商品已经打包了数量
				if (StringUtils.isNotEmpty(goodsCart.getTableNo())) {
					goodsCartExtend.setTableNo(goodsCart.getTableNo());
					cart = goodsCartServiceApi.getSamePropGoodsByTableNo(goodsCartExtend);
				} else {
					cart = goodsCartServiceApi.getSamePropGoodsByBuyerId(goodsCartExtend);
				}
				if(cart!=null){
					//删除打包的购物车
					goodsCartExtend.setGoodsDesc("打包");
					deleteShopCartByPack(goodsCartExtend);
					//更新不打包商品数量
					GoodsCartAndDetail goods = new GoodsCartAndDetail();
					goods.setGoodsDesc("");
					goods.setId(cart.getId());
					goods.setBuyCount(Arith.add(goodsCart.getBuyCount(),cart.getBuyCount()));
					goodsCartServiceApi.updateGoodsCart(goods);
				}
			}
		}
		
		//将购物车中goodsDesc存在打包字样的全部改为""
		String goodsDesc = "";
		updateGoodsCartByGoodsDesc(storeId, tableName, buyerId, goodsDesc);
		isOutMap.put("isOut", new Integer(1));
		res.setData(isOutMap);
		res.setMsg("整单打包成功");
		return res;
	}

	@Override
	public CoreResponse<Map<String, Integer>> updateRemoveSinglePackGoods(Integer goodsCartId) {
		CoreResponse<Map<String, Integer>> res = new CoreResponse<Map<String, Integer>>();
		//获取购物车商品信息
		GoodsCartAndDetail goodsCart = getShopCartById(goodsCartId);
		//如果该商品没有打包，直接返回
		if (goodsCart==null || StringUtils.isEmpty(goodsCart.getGoodsDesc()) || !goodsCart.getGoodsDesc().contains("打包")) {
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setMsg("打包失败，同桌已下单或者删除了该菜品");
			return res;
		}
		Map<String, Integer> isOutMap = new HashMap<String, Integer>();
		GoodsCart cart = new GoodsCart();
		//组合套餐直接取消(没有合并)
		if (new Integer(2).equals(goodsCart.getIsPackage())) {
			cart.setBuyCount(goodsCart.getBuyCount());
		} else {
			GoodsCartExtend goods = new GoodsCartExtend();
			goods.setStoreId(goodsCart.getShopperId());
			goods.setGoodsId(goodsCart.getGoodsId());
			goods.setBuyerId(goodsCart.getBuyerId());
			goods.setTableNo(goodsCart.getTableNo());
			goods.setSizeId(goodsCart.getSizeId());
			goods.setPropIds(goodsCart.getPropIds());
			goods.setGoodsDesc("");
			Integer count = getShopCartByPack(goods);
			// 没有同菜品不打包的记录
			if (count >= 1) {
				cart.setBuyCount(Arith.add((goodsCart.getBuyCount()), (double) count));
				deleteShopCartByPack(goods);
			} else {
				cart.setBuyCount(goodsCart.getBuyCount());
			}
		}
		cart.setId(goodsCart.getId());
		cart.setGoodsDesc("");
		updateGoodsCartById(cart);
		isOutMap.put("isOut", new Integer(0));
		res.setData(isOutMap);
		res.setMsg("取消打包成功");
		return res;
	}

	@Override
	public CoreResponse<Map<String,Object>> deleteShopCartById(DeleteShopCartIdEntryVO shopCartIdEntryVO) {
		
		CoreResponse<Map<String,Object>> res = new CoreResponse<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("isOut", 0);
		int deleteCount = goodsCartServiceApi.deleteGoodsCartById(shopCartIdEntryVO.getGoodsCartId());
		Integer isOut = shopCartIdEntryVO.getIsOut()==null?0:shopCartIdEntryVO.getIsOut();
		if(deleteCount==0){
			res.setStatusInfo(StatusInfo.FORBIDDEN);
			res.setData(map);
			res.setSubMsg("该商品已被删除");
			return res;
		}
		// 获取redis店铺配置信息
		Object config = redisService.getObj(shopCartIdEntryVO.getStoreId() + "_shopperConfig");
		ShopperConfigExtend shopperConfigExt = null;
		if (config == null) {
			// 查询店铺所有配置
			Map<String, Object> shopConfig = shopperInfoServiceApi.getShopperAllConfig(shopCartIdEntryVO.getStoreId());
			// map转成对象
			shopperConfigExt = SweepOrderUtils.convertToShopperConfigVO(shopConfig);
		} else {
			shopperConfigExt = (ShopperConfigExtend) config;
		}
		//合并打包商品
		if (deleteCount > 0 && !new Integer(1).equals(isOut) && !Constants.clientOrderMode.ONLINE_ORDER_MODE.getValue()
				.equals(shopCartIdEntryVO.getClientOrderMode())) {
			String createDate = DateUtils.getYesterdayStartTime();
			String endDate = DateUtils.getTodayEndTime();
			List<GoodsCartAndDetail> goodsCartList = null;
			//根据桌台获取商品数据
			if (!StringUtils.isEmpty(shopCartIdEntryVO.getTableName())) {
				if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
					// 如果开启同桌单点就根据桌台和顾客Id查询
					goodsCartList = goodsCartServiceApi.getGoodsCartByTableNoAndBuyerId(shopCartIdEntryVO.getStoreId(),
						shopCartIdEntryVO.getTableName(), createDate, endDate, shopCartIdEntryVO.getBuyerId());
				} else {
					goodsCartList = goodsCartServiceApi.getGoodsCartByTableNo(shopCartIdEntryVO.getStoreId(),
						shopCartIdEntryVO.getTableName(), createDate, endDate,shopCartIdEntryVO.getClientOrderMode());
				}
			} else {
				// 根据顾客id获取数据
				goodsCartList = goodsCartServiceApi.getGoodsCartByBuyerId(shopCartIdEntryVO.getStoreId(),
					shopCartIdEntryVO.getBuyerId(), createDate, endDate,shopCartIdEntryVO.getClientOrderMode());
			}
			boolean flag = true;
			if (CollectionUtils.isEmpty(goodsCartList)) {
				res.setData(map);
				return res;
			}
			//如果goods_desc都为打包则isOut为整单打包
			for(GoodsCartAndDetail cart:goodsCartList){
				if(!CommConstant.GOODS_DESC.equals(cart.getGoodsDesc())){
					flag = false;
				}
			}
			if (!flag) {
				res.setData(map);
				return res;
			}
			String goodsDesc ="";
			int updateCount = 0;
			if (!StringUtils.isEmpty(shopCartIdEntryVO.getTableName())) {
				if (shopperConfigExt != null && new Integer(1).equals(shopperConfigExt.getFirstPayMent()) && new Integer(1).equals(shopperConfigExt.getIsOpenDeskmateSinglePoint())) {
					// 如果开启同桌单点就根据桌台和顾客Id修改
					updateCount = goodsCartServiceApi.updateGoodsCartPackByTableNoAndBuyerId(shopCartIdEntryVO.getStoreId(), shopCartIdEntryVO.getTableName(), goodsDesc, shopCartIdEntryVO.getBuyerId());
				} else {
					updateCount = goodsCartServiceApi.updateGoodsCartPackByTableNo(shopCartIdEntryVO.getStoreId(), shopCartIdEntryVO.getTableName(), goodsDesc);
				}
			}else{
				updateCount = goodsCartServiceApi.updateGoodsCartPackByBuyerId(shopCartIdEntryVO.getStoreId(), shopCartIdEntryVO.getBuyerId(), goodsDesc);
			}
			if(updateCount > 0){
				map.put("isOut", 1);
			}
		}
		res.setData(map);
		return res;
	}

	@Override
	public void updateNeedGoods(Integer storeId, String buyerId, String tableName) {
		if (!StringUtils.isEmpty(tableName)) {
			goodsCartServiceApi.updateNeedGoodsByTableNo(storeId, tableName);
		} else {
			goodsCartServiceApi.updateNeedGoodsByBuyerId(storeId, buyerId);
		}
	}

}
